package com.lbd.util;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by lance on 2016/11/21.
 */
public class PdfUtils {
    private static String tmpdir = PdfUtils.class.getResource("/").getPath() + "tmpdir";

    {
        tmpdir = tmpdir.replaceAll("^/", "");
    }

    //
    public String generationPdfByContent(String content, String cmdPath, String code) throws Exception {
        String tmpFileName = UUID.randomUUID().toString(); //生成随机文件名
//        System.out.println("content:"+content);
        File dir = new File(tmpdir);
        if (!dir.exists())
            dir.mkdirs();
        String htmlFileName = tmpdir + "/" + tmpFileName + ".html";
        PrintWriter pw = new PrintWriter(
                new OutputStreamWriter(
                        new FileOutputStream(htmlFileName),
                        code));
        pw.print(content);
        pw.close();

        String pdfFileName = tmpdir + "/" + tmpFileName + ".pdf";
        File pdfFile = new File(pdfFileName); //pdf文件
        String command = getCommand(htmlFileName, pdfFileName, cmdPath);
        Runtime.getRuntime().exec(command);
        return pdfFile.getAbsolutePath();
    }

    public String generationPdfByUrl(String url, String cmdPath) throws Exception {
        String tmpFileName = UUID.randomUUID().toString(); //生成随机文件名
        File dir = new File(tmpdir);
        if (!dir.exists())
            dir.mkdirs();
        String pdfFileName = tmpdir + "/" + tmpFileName + ".pdf";
        File pdfFile = new File(pdfFileName); //pdf文件
        String command = getCommand(url, pdfFileName, cmdPath);
        Runtime.getRuntime().exec(command);
        return pdfFile.getAbsolutePath();
    }

    public String getCommand(String htmlName, String pdfName, String cmdPath) {
        String system = System.getProperty("os.name");
        if ("Windows xp".equalsIgnoreCase(system))   //win xp系统
            return cmdPath + " " + htmlName + " " + pdfName;
        else if ("Windows 7".equalsIgnoreCase(system))   //win7系统
            return cmdPath + " " + htmlName + " " + pdfName;
        else if ("Linux".equalsIgnoreCase(system))  //linux 系统
            return cmdPath + " " + htmlName + " " + pdfName;
        return "";
    }

//    public static void main(String[] args){
//        PdfUtils pdfTool = new PdfUtils();
//        String command = pdfTool.getCommand("http://www.baidu.com", "E:/test2.pdf");
////        System.out.println(command);
//        try {
//            Runtime.getRuntime().exec(command);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
}
